<?php
require_once 'inc.php';


while (1)
{
	$id = get_next_index();
	$url = sprintf("http://wallbase.net/wallpaper/%d", $id);

	$page_dir = PAGE_BASE_HASH_DIR.floor($id/HASH_NUMBER);
	$image_dir = IMAGE_BASE_HASH_DIR.floor($id/HASH_NUMBER);

	$page_file = $page_dir."/$id.html";
	$image_file = $image_dir."/$id.jpg";
	//echo $image_file;exit;

	if (file_exists($image_file) && filesize($image_file)) continue;

	if (file_exists($page_file) && filesize($page_file))
	{
		echo $page_file;exit;
		$page = file_get_contents($page_file);
	} else {
		$page = file_get_contents($url);
		file_put_contents($page_file, $page);

		$page_size = strlen($page);
		sys::sql("insert into wallbase_download_stats (image_index, page_size)"
			."values (%d, %d) on duplicate key update page_size='%d';",
			$id, $page_size, $page_size);
	}

	if (empty($page)) continue;
	
	preg_match("<img src='(.*?)' alt=\"(.*?)\" \/>", $page, $m);
	$image_url = $m[1];
	$image_text = $m[2];

	if (empty($image_url)) continue;

	$t = explode('/', $image_url);
	echo $image_file."\n";

	$tmp_file = "_ing/".$id.".jpg";
	copy($image_url, $tmp_file);
	
	if (!file_exists($tmp_file)) continue;
	
	rename($tmp_file, $image_file);

	$image_size = file_exists($image_file) ? filesize($image_file) : 0;
	$sql = sys::getSqlString("insert into wallbase_download_stats (image_index, image_size)"
		."values (%d, %d) on duplicate key update image_size='%d';",
		$id, $image_size, $image_size);
	sys::sql($sql);
}

function get_next_index()
{
	$result = sys::sql("select * from wallbase_download_stats where"
		." ((image_size=0 and page_size>0 and page_size<15000)"
		." or page_size=0) order by rand() limit 1;");
	if (empty($result)) exit;
	return $result[0]['image_index'];
}

function tempnam_sfx($path, $suffix)
{
	do
	{
		$file = $path."/".mt_rand().$suffix;
		$fp = @fopen($file, 'x');
	}
	while(!$fp);
	
	fclose($fp);
	return $file;
}